# -*-coding:utf-8 -*-

import docx2txt
import xlrd
import platform
if 'Windows' in platform.system():
    from win32com import client


# Linux下要预装antiword来处理doc文件
import subprocess


def docxText(filePath):
    try:
        text = docx2txt.process(filePath)
        return text
    except:
        text = xls_txt(filePath)
        return text


def docTOdocxLinux(filePath):  
    # filePath:文件地址 ， awordPath：安装的antiword的地址
    word_file = filePath
    content = subprocess.check_output(['antiword', word_file])
    return content

def docTOdocx(doc_name, docx_name):
    try:
        word = client.Dispatch("Word.Application")
        doc = word.Documents.Open(doc_name)
        doc.SaveAs(docx_name, 12)  # 16是保存为doc，转化成docx是12
        doc.Close()
        word.Quit()
    except Exception as e:
        print e


def docText(filePath):
    path = filePath[-3:]  # 此处不知道该怎么区分xls与doc
    if 'doc' == path:
        docPath = filePath + 'x'
        docTOdocx(filePath, docPath)
        return docxText(docPath)
    else:
        text = xls_txt(filePath)
        return text


def strs(row):
    """
    :返回一行数据
    """
    try:
        values = ""
        for i in range(len(row)):
            if i == len(row) - 1:
                values = values + str(row[i])
            else:
                # 使用“，”逗号作为分隔符
                values = values + str(row[i]) + ","
        return values
    except:
        raise


def xls_txt(xls_name):
    """
    :excel文件转换为txt文件
    :param xls_name excel 文件名称
    """
    text = ''
    try:
        data = xlrd.open_workbook(xls_name)
        table = data.sheets()[0]  # 表头
        nrows = table.nrows  # 行数
        # 如果不需跳过表头，则将下一行中1改为0
        for ronum in range(0, nrows):
            row = table.row_values(ronum)
            values = strs(row)  # 条用函数，将行数据拼接成字符串
            text += values  # 将字符串写入新文件
        sqlfile.close()  # 关闭写入的文件
    except:
        pass
    # print('>>>>', text)
    return text


# if __name__ == '__main__':
#     xls_name = 'E:\programs\\tecProj\\tempTest\\tempFiles\\excelOne.xlsx'
#     xls_txt(xls_name)
